<template>
  <div class="questList-box">
    <el-row :gutter="5">
      <el-col :span="2"><el-button @click="multiDel">删除</el-button></el-col>
      <el-col :span="2"><el-button @click="() => {this.dialogVisible = true}">导入</el-button></el-col>
      <el-col :span="2"><el-button @click="dc"><a :href="exportUrl" class="upload_te">导出</a></el-button></el-col>
      <!-- <el-col :span="2"><el-button @click="() => {this.$message.info(`此功能还在开发中`)}">导入</el-button></el-col> -->
  		<el-col :span="2"><el-button @click="() => {this.$router.push('questAddForm')}">新增</el-button></el-col>
  		<el-col :span="3" :offset="2">
        <template>
          <el-select v-model="value_c" clearable placeholder="请选择分类">
            <el-option
              v-for="item in options_c"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </template></el-col>
  		<el-col :span="3">
  			<template>
				  <el-select v-model="value" clearable placeholder="请选择题型">
				    <el-option
				      v-for="item in options"
				      :key="item.value"
				      :label="item.label"
				      :value="item.value">
				    </el-option>
				  </el-select>
				</template></el-col>
			<el-col :span="3">
  			<template>
				  <el-select v-model="value_n" clearable placeholder="请选择难易程度">
				    <el-option
				      v-for="item in options_n"
				      :key="item.value"
				      :label="item.label"
				      :value="item.value">
				    </el-option>
				  </el-select>
				</template></el-col>
  		<el-col :span="3"><el-input v-model="input" placeholder="请输入关键词"></el-input></el-col>
  		<el-col :span="2"><el-button  @click="keywordSearch" plain>搜索</el-button></el-col>
  	</el-row>
    <Table
			ref='selectall'
      :tableData="tableData"
      :inits="tableinits"
      canSelect
			@select="select_table"
      :operation="operationinits">
      <template slot-scope="rowScope">
        <el-button @click="check(rowScope)" type="text" size="small">查看</el-button>
        <el-button @click="edit(rowScope)" type="text" size="small">编辑</el-button>
        <el-button @click="del(rowScope)" type="text" size="small">删除</el-button>
      </template>
    </Table>
    <!-- 分页器 S -->
    <el-row>
      <el-col>
        <el-pagination
          layout="prev, pager, next"
          :page-size="15"
          ref='pagination'
          :current-page="pageNo"
          :total="total"
          @current-change="pageNoChange">
        </el-pagination>
      </el-col>
    </el-row>
    <!-- 分页器 E -->
    <!-- 导入弹窗 S -->

    <el-dialog
      title="导入题库"
      :visible.sync="dialogVisible"
      width="44%"
      :before-close="closeHandle">

       <el-upload
					  class="upload-demo"
					  drag
					  ref="upload"
					  :action="exportUrldaoques"
					  :show-file-list="false"
					  :on-success="handSuccess"
		        :on-remove="handleRemove"
		        :file-list="fileList"
		        :before-upload="beforeAvatarUpload"
            :on-progress="uploadProgress"
            :disabled="uploading"
					  multiple>
					  <i :class="[uploading ? 'el-icon-loading' : 'el-icon-upload']"></i>

					  <div v-if="uploading" class="el-upload__text">正在导入，请等待</div>
					  <div v-else class="el-upload__text">将文件拖到此处，或<em>点击上传<p></p></em></div>

					  <div class="el-upload__tip tishi" slot="tip" v-show="ok">共上传 {{sum}} 行，成功上传 {{succes}} 行</div>

					</el-upload>
					<a :href="exportUrlupques" class="Download_te">下载模板</a>
	      			<el-table v-show="ok"
						      :data="retureData"
						      style="width: 100%"
                  :height="250"
                  size="small">
						      <el-table-column
						        prop="row"
						        label="错误行数"
						        width="180">
						      </el-table-column>
						      <el-table-column
						        prop="error"
						        label="错误原因">
						      </el-table-column>
						</el-table>

    </el-dialog>
    <!-- 导入弹窗 E -->
  </div>
</template>

<script>
import Table from '@/components/Table'
import { quest_fmt_getQuestions } from '@/util/dataFMT'
import { FILE_UPLOAD_LIMIT } from '@/global_Init'
import multidel from '@/mixins/multidel'

export default {
  name: 'QuestList',
  components: {
    Table
  },
  mixins: [multidel],
  mounted () {
//     this.$API.getQuestions({page: this.pageNo})
//     .then(data => {
//       this.total = data.total
//       this.tableData = quest_fmt_getQuestions(data.data)
//     })
		this.pageNoChange(window.questList||this.pageNo)
    this.$API.getAllQuestClass()
    .then(data => {
      this.options_c = data.map(item => {
        return {label: item.name, value: item.id}
      })
    })
  },
  data () {
    return {
      uploading: false,
      pageNo:window.questList || 1,
      total: 0,
      page:10,
      sum:'',
      succes: '',
      ok:false,
      saas_user_id:'',
			history:{},
      dialogVisible: false,
      fileList: [],
    	input: '',
      tableData: [],
      retureData:[{row:'',error:''}],
      tableinits: [
        { label: '编号', width: '80', prop: 'code' },
        { label: '题目', prop: 'name', notooltip: true},
        { label: '题型', width: '50', prop: 'type' },
        { label: '难易', width: '50', prop: 'degree' },
        { label: '分类', width: '100', prop: 'class' },
        { label: '参考文献', width: '200', notooltip: true, prop: 'literature' },
//      { label: '适用人群', width: '120', prop: 'intend' },
        { label: '标签', width: '120', prop: 'tag' },
        { label: '更新时间', width: '120', prop: 'updateTime' },
        { label: '创建时间', width: '120', prop: 'createTime' }
      ],
      operationinits: { width: '140', label: '操作' },
      options_c: [],
      value_c: '',
      options: [
        {
          value: 'single',
          label: '单选'
        }, {
          value: 'multiple',
          label: '多选'
        }, {
          value: 'judge',
          label: '判断'
        }, {
          value: 'text',
          label: '填空'
        }, {
          value: 'composite',
          label: '问答'
        }
      ],
    	value: '',
    	options_n: [
        {
          value: 'easy',
          label: '简单'
        }, {
          value: 'medium',
          label: '中等'
        }, {
          value: 'hard',
          label: '困难'
        }
      ],
      value_n: ''
		}
  },
  computed: {
    exportUrl() {
      return `${EHS.HOST}/api/v1/export/question?saas=${this.saas_user_id}`
    },
    exportUrldaoques(){
    	return `${AOSAIBAN.HOST}/api/v1/import/question`
    },
    exportUrlupques(){
    	return `${EHS.HOST}/api/v1/import/template/question`
    },
    queryParams () {
      this.pageNo = window.questList || 1
      return { category_id: this.value_c, type: this.value, difficulty: this.value_n }
    }
  },
  watch: {
    queryParams (curr, old) {
      this.history = {};
      this.$API.getQuestions(Object.assign({page: this.pageNo, keyword: this.input}, curr))
      .then(data => {
        this.total = data.total
        this.tableData = quest_fmt_getQuestions(data.data)
      })
    },
    history (curr) {
      let arr = []
      for (const propname in curr) {
        arr = arr.concat(curr[propname])
      }
      this._mixSelectionChange(arr)
    },
  },
  created: function () {
  	var user_info =JSON.parse(localStorage.getItem('userinfo'));  //个人信息
    this.saas_user_id=user_info.saas_user_id;

  },
  methods: {
    multiDel () {
      this._mixMutiDel(`delQuestion`, () => {
        this.history = {}
        this.pageNoChange(1)
      })
    },
    closeHandle (done) {
      if (!this.uploading) {
        done()
      }
    },
    uploadProgress () {
      if (!this.uploading) {
        this.uploading = true
      }
    },
		select_table(row){
			this.history['index'+this.pageNo] = JSON.parse(JSON.stringify(row));
      this.history = Object.assign({}, this.history);
		},
    keywordSearch () {
		   this.pageNoChange(1)
    },
    pageNoChange (pageNo) {
      this.pageNo = pageNo;
      window.questList = pageNo
      let _this = this;
      this.$refs.pagination.internalCurrentPage = pageNo
      this.$API.getQuestions(Object.assign({page: this.pageNo, keyword: this.input}, this.queryParams))
      .then(data => {
        this.tableData = quest_fmt_getQuestions(data.data)
        this.total = data.total
        this.tableData.forEach((item,index)=>{
            item.code = ((pageNo-1)*10)+(index+1)
        })
				if(this.history['index'+pageNo]){
					this.tableData.forEach((item,index)=>{
						_this.history['index'+pageNo].forEach(ids =>{
							if(ids.id == item.id){
								item._select = true;
							}
						})
					})
				}
				_this.$nextTick(()=>{
					_this.tableData.forEach(item=>{
						if(item._select){
							_this.$refs.selectall.toggleRowSelection(item,true)
						}
					})
				})
      })
    },
    check ({rowScope}) {
      // localStorage.setItem('q_tocheck_status', JSON.stringify({
      //   input: this.input,
      //   value_c: this.value_c,
      //   value: this.value,
      //   value_n: this.value_n,
      //   pageNo: this.pageNo
      // }))
      this.$router.push({path: `questDetail/${rowScope.row.id}`})
    },
    edit ({rowScope}) {
      this.$router.push({path: `questAddForm/${rowScope.row.id}`})
    },
    del ({rowScope}) {
    	this.$confirm('确认删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
    	.then(() => {
	     		this.$API.delQuestion(rowScope.row.id)
			    .then(data => {
			        this.tableData.splice(this.tableData.findIndex((el) => {
			          return el.id === rowScope.row.id
			        }), 1)
              this.pageNoChange(1)
			      })
		     .catch(errmsg => {
		        this.$message({
	            type: 'error',
	            message: errmsg
		      	});
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
      	});

    },
    handleClose () {
      console.log(`dialog closed`)
      this.dialogVisible = false;
      this.retureData=[{row:'',error:''}];
      this.ok=false;
    },
    submit () {
      console.log(`submit clicked`)
      // this.submitUpload();
      this.dialogVisible = false;
      this.$refs.upload.submit();
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
    },
    handSuccess(response, file, fileList){
    	this.retureData=response.data.errors;
    	this.sum=response.data.total;
    	this.succes=response.data.success;
    	if(response.data.total!=response.data.success){this.ok=true;}
    	else{this.$message.success(`上传文件成功`);}

      this.$nextTick(() => {this.uploading = false})
    },
    handlePreview(file) {
    },
     beforeAvatarUpload(file) {
      let isture=false;
      if(file.name.match(/\.(xlsx|xls|xlsm|csv)$/i)){isture=true;}
//    const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < FILE_UPLOAD_LIMIT;

        if (!isture) {
        	 this.$refs.upload.abort();
          this.$message.error('上传文件只能是 Excel 文件!');

        }
       if (!isLt2M) {
         this.$message.error(`上传文件大小不能超过 ${FILE_UPLOAD_LIMIT}MB!`);
       }
        return isture && isLt2M;
   },
   dc () { // 导出按钮被按下

    }
  }
}
</script>

<style>
  .questList-box {
    text-align: left;
  }
  .el-upload-dragger{height: 160px !important;}
  .tishi{font-size: 16px !important;text-align: center !important;margin-bottom: 8px !important;}
  .Download_te{float: right;color: #0366bb ;text-decoration: none;}
  .Download_te:hover{text-decoration: underline;}
  .upload_te{color: #606266 !important;text-decoration: none;}
  .upload-demo {
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
  }
  .upload-demo .el-icon-loading{
    font-size: 30px;
    margin-top: 60px;
  }
</style>
